package com.topdt.jbpm.extension;

import java.util.List;

import org.jbpm.api.jpdl.DecisionHandler;
import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.model.Transition;
//import org.jbpm.api.model.Transition;
import org.jbpm.pvm.internal.model.ActivityImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;

import com.topdt.jbpm.model.Activity;
import com.topdt.jbpm.service.Context;
import com.topdt.jbpm.service.JbpmService;
import com.topdt.jbpm.utils.DecisionBranchUtil;


/**
 *  @Project       : saasoa
 *  @Program Name  : com.topdt.jbpm.extension.DecisionBranchHandler.java
 *  @Class Name    : QuantityDecisionHandler
 *  @Description   : 决定节点处理handler,封装了业务处理规则,会自动的进行流程的流转,在节点到达decision时执行
 *  @Author        : calonlan
 *  @Creation Date : 2014年12月9日 上午9:23:43
 *  @ModificationHistory
 *  Who        When          What
 *  --------   ----------    -----------------------------------
 *  username   2014年12月9日       TODO
 */
public class DecisionBranchHandler implements DecisionHandler{


	/**
	 * serialVersionUID : TODO（用一句话描述这个变量表示什么）
	 * @since   : v1.00
	 */

	private static final long serialVersionUID = -8815807796100971203L;
	private Context context;
	private JbpmService jbpmService;



	public String decide(OpenExecution execution) {
		//获取到决定节点的所有外出activity
		this.context = (Context) execution.getVariable(Context.KEY);
		this.jbpmService = JbpmService.getJbpmService();
		ExecutionImpl exe = (ExecutionImpl) execution;
		ActivityImpl act = exe.getActivity();
		List<Transition> outs = (List<Transition>) act.getOutgoingTransitions();

		/*//循环决定节点的所有向前流转，根据业务规则自动判断执行
		//数字区间业务关键字段,例如:day
		String key = null;
		//业务关键字段在表单的值
		String val = null;
		//分支返回的结果
		boolean result = false;
		boolean numFlag = false;
		boolean roleFlag = false;
		List<Role> roles = null;*/
		DecisionBranchUtil branchUtil = new DecisionBranchUtil();

		for(Transition tran : outs) {
			org.jbpm.api.model.Activity activity = tran.getDestination();
			Activity a = jbpmService.getActivityDao().getActivityById(context.getFlowId(), activity.getName());
			/*String str = a.getDesc();
			//去除空白
			str = str.replaceAll("\\s*", "");

	    	System.out.println("str:"+str);
	    	if(str != null && str.length() > 0) {
	    		String[] arr = str.split(":");
	    		//决定类型:数字区间
	    		if("num".equals(arr[0])) {
	    			if(!numFlag) {

	    	    		//匹配关键字
	    		    	Pattern p = Pattern.compile("[A-Za-z]+");
	    		        Matcher m = p.matcher(arr[1]);
	    		        if(m.find()) {
	    		        	key = m.group();
	    		        }
	    		        //获取关键字段在表单的值
	    		        FormInstanceManager formInstanceManager = (FormInstanceManager) SysContext.getBean(FormInstanceManager.class);
	    				Map<String, String> data = formInstanceManager.getDataById(context.getWorkId());
	    				val = data.get(key);
	    				numFlag = true;
	    	    	}

	    			//匹配
//	    	        boolean flag = MatchUtil.intervalMatch(key, Float.valueOf(val),str);
	    	    	result = LogicalUtil.parse(Float.valueOf(val), key, arr[1]);
	    		//决定类型:角色区间
	    		} else if("role".equals(arr[0])) {

	    			if(!roleFlag) {
	    				IdentityService identityService =
		    					(IdentityService) SysContext.getBean(IdentityService.class);
		    			roles = identityService.getRolesOfUser(context.getCurrentActor());
	    				roleFlag = true;
	    			}
	    			result = roleMatch(roles, arr[1]);
	    		}
	    	}*/
			boolean result = branchUtil.isBranchMatch(a, context);
	        if(result) {
	        	return tran.getName();
	        }

		}
		//如果没有指定规则，默认第一个出口
		return outs.get(0).getName();
	}

}
